import type { DropdownItemOption } from 'vant';
import { GameConfig, GameId, SearchConfigDealItem, SearchMapItem } from '/@/api/general/model/cardModel';
import { SearchMapValTypeEnum } from '/@/api/general/model/cardModel';
import { reactive } from 'vue';
import { awaitWrap } from '/@/utils';
import { CardGameConfigApi, CardSearchConfigApi } from '/@/api/general/card';

// 游戏配置
const gameConfigData = reactive<GameConfig>({} as GameConfig);
// 列表搜索配置
const gameSearchConfigData = reactive<SearchConfigDealItem[]>([]);

const getGameConfig = (params: GameId) => {
  const gameConfig = async () => {
    const [error, result] = await awaitWrap(CardGameConfigApi({ game_id: params.game_id }));
    if (error || !result) {
      return;
    }
    for (const item in result) {
      gameConfigData[item] = result[item];
    }
  };
  gameConfig();
};

const getSearchConfig = (params: GameId) => {
  const handleSearchMapping = (mapping: SearchMapItem[]) => {
    const resultMapping: DropdownItemOption[] = [];
    for (const mapItem of mapping) {
      resultMapping.push({
        value: mapItem.key,
        text: mapItem.value,
        icon: mapItem.value_type === SearchMapValTypeEnum.IMAGE ? mapItem.value : '',
      });
    }
    return resultMapping;
  };
  const searchConfig = async () => {
    const [error, result] = await awaitWrap(CardSearchConfigApi({ game_id: params.game_id }));
    if (error || !result) {
      return;
    }
    gameSearchConfigData.length = 0;
    for (const searchItem of result) {
      const resultMapping = handleSearchMapping(searchItem.mapping);
      gameSearchConfigData.push({
        title: searchItem.title,
        attr_key: searchItem.attr_key,
        search_style: searchItem.search_style,
        search_logic: searchItem.search_logic,
        mapping: resultMapping,
      });
    }
  };
  searchConfig();
};

export const useGeneralGameHooks = () => {
  return {
    gameConfigData,
    gameSearchConfigData,
    getGameConfig,
    getSearchConfig,
  };
};
